<template>
  <div class="right-list">
    <header class="main-title">
      <div class="main-label">菜单权限</div>
      <el-button color="#6C52EA" @click="handleSave">保存</el-button>
    </header>
    <div class="menu-tree">
      <el-tree
        :default-checked-keys="cheackId"
        ref="treeRef"
        :data="menuData"
        show-checkbox
        highlight-current
        node-key="id"
        :props="defaultProps"
      >
      </el-tree>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElTree } from 'element-plus'

import { PropType, ref, watch } from 'vue'
// import { IroleData, IroleMenuData } from '../config/menuRole'
import { getMenuList } from '@/apis/jurisdiction/menu'
import { IroleData, IroleMenuData } from '../config/menuRole'
import { Itype } from '@/type'
import {
  createPostReq,
  deleteMenuRoleData,
  getMenuRoleList,
  getRoleList
} from '@/apis/jurisdiction/role'
// import { createPostReq, getMenuRoleList, deleteMenuRoleData } from '@/apis/auth/role_menu'
import { usePermission } from '@/hooks/usePermission'

const props = defineProps({
  roleDatas: {
    type: Object as PropType<IroleData>,
    default: () => {}
  }
})

const treeRef = ref<InstanceType<typeof ElTree>>()
const roleData = ref<IroleData>()
const cheackId = ref()
watch(
  () => props.roleDatas,
  (newVal) => {
    treeRef.value?.setCheckedKeys([])
    if (newVal?.role_menu && newVal?.role_menu.length) {
      cheackId.value = []
      newVal?.role_menu.forEach((item: { menu_id: number; d_parameter: number }) => {
        if (item.d_parameter !== 0) {
          cheackId.value.push(+item.menu_id)
        }
      })
    }
    roleData.value = newVal
  },
  { immediate: true }
)

const dialog = ref(false)
const defaultProps = {
  children: 'children',
  label: 'name'
}

/**
 * @desc:获取菜单列表数据
 *
 */
const loading = ref(false)
let menuData = ref()
const getData = (data?: string) => {
  loading.value = true
  getMenuList()
    .then((res) => {
      if (res) {
        menuData.value = res
        menuData.value.forEach((element: Itype) => {
          element.created_at = new Date(
            +new Date(new Date(element.created_at).toJSON()) + 8 * 3600 * 1000
          )
            .toISOString()
            .replace(/T/g, ' ')
            .replace(/\.[\d]{3}Z/, '')
        })
      }
      loading.value = false
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

getData()

/**
 * 保存关闭
 */
const emit = defineEmits(['reFresh'])
const handleSave = () => {
  if (!props.roleDatas) {
    ElMessage.error('请先选择父级角色！')
    return false
  }
  let checkNodes = treeRef.value!.getCheckedNodes()
  let halfNodes = treeRef.value!.getHalfCheckedNodes() //半选的数据
  let arr: any[] = []
  checkNodes.forEach((item) => {
    if (!item.children.length) {
      arr.push({
        menu_id: item.id,
        role_id: roleData.value?.id,
        d_parameter: 1,
        permission_code: item.permission_code
      })
    } else {
      arr.push({
        menu_id: item.id,
        role_id: roleData.value?.id,
        d_parameter: 0,
        permission_code: item.permission_code
      })
    }
  })
  halfNodes.forEach((item) => {
    arr.push({
      menu_id: item.id,
      role_id: roleData.value?.id,
      d_parameter: 0,
      permission_code: item.permission_code
    })
  })
  getMenuRoleList({
    role_id: roleData.value?.id
  })
    .then((res) => {
      if (!res) return
      let arrId: any[] = []
      res.map((item: IroleMenuData) => {
        arrId.push(item.id)
      })
      if (arrId && arrId.length) {
        // 批量角色id对应数据
        deleteMenuRoleData(arrId)
      }
      if (arr) {
        // 批量增加角色对应菜单数据
        createPostReq(arr).then((res) => {
          if (!res) return
          emit('reFresh')
          ElMessage.success('操作成功！')
        })
      }
    })
    .catch((err) => {
      ElMessage.error('服务器内部错误！')
    })
}

/**
 * @desc:关闭dialog
 */
const dialogClose = () => {
  dialog.value = !dialog.value
}
</script>

<style lang="less" scoped>
.right-list {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
  .main-title {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 10px 0;
    .main-label {
      font-size: 18px;
      color: rgba(0, 0, 0, 0.65);
      font-weight: 700;
    }
  }
  .menu-tree {
    flex: 1;
    overflow: auto;
  }
}
</style>

function filterItem(item: Itype, data: string) {
  throw new Error('Function not implemented.')
}
